<?php

/**
 * 自动生成 SysGroupService
 * 
 * Apps/Common/Service/SysGroupService.class.php
 * admin @ 2015-06-25
 */

namespace Common\Service;

class SysGroupService {

  private static $instance;
  
  public static function instance() {
    if (self::$instance == null) {
      $instance = new SysGroupService();
    }
    return $instance;
  }

  function get_default_row() {
    return array(
      'sort' => '99',
      'pid'  => '0',
      'sys_type' => 2 ,
      'name' => '',
      'desc' => '',
      'expand' => '',
      'status' => 1,
      'level' => '1',
    );
  }
  
  function get_by_user_id( $user_id , $group_concat_group = FALSE ) {
    $SysUserGroup = M('SysUserGroup');
    $SysUserGroup->alias('sug');
    if ( $group_concat_group  ) {
      $SysUserGroup->field( ' GROUP_CONCAT(sug.group_id) as group_id ' );
    }
    $SysUserGroup->join('sys_group sg on sg.id = sug.group_id');
    $data = $SysUserGroup->where('sug.user_id = %d' , $user_id )->find();
    return $data ? $data : array();
  }
  
  function get_by_user_id_for_auth( $user_id ) {
    $SysUserGroup = M('SysUserGroup');
    $data = $SysUserGroup
            ->alias('sug')
            ->field( ' GROUP_CONCAT( sug.group_id ) AS group_id , GROUP_CONCAT( sg.name ) AS group_name ' )
            ->join('sys_group sg on sg.id = sug.group_id')
            ->where('sug.user_id = %d' , $user_id )
            ->find();
    return $data ? $data : array();
  }
      
  function get_by_id($id) {
    $SysGroup = M('SysGroup');
    $data = $SysGroup->find($id);
    return $data ? $data : array();
  }

  function get_level( $pid ) {
    if ( empty( $pid ) ) {
      return 1 ;
    }
    $data = $this->get_by_id($pid);
    if ( empty( $data ) ) {
      return 1 ;
    }
    return $data['level'] + 1 ;
  }
  
  function get_by_cond($config) {
    $default = array(
      'pid' => 0 ,
      'mer_id' => 0 ,
      'sys_type' => '',
      'status' => '',
    );

    $config = extend($config, $default);
    $where = array(
      'sg.id' => array('NEQ' , 0 )
    );
    if (!empty($config['status'])) {
      $where['sg.status'] = $config['status'];
    }
    
    if ( empty($config['mer_id']) ) {
      $where['sg.mer_id'] = 0 ;
    } else {
      $where['sg.mer_id'] = $config['mer_id'] ;
    }
    
    if ( !empty($config['sys_type']) ) {
      $where['sg.sys_type'] = $config['sys_type'];
    }
    
    $SysGroup = M('SysGroup');
    $order = ' level ASC , sort ASC ';
    $data = $SysGroup->alias('sg')
      ->field('sg.*, sd.text as sys_type_text ' )
      ->join('sys_Dictionary sd on sd.id = sg.sys_type' , 'left')
      ->where($where)->order($order)->select();

    //echo $SysGroup->_sql();
    $result = array();
    $index = array();

    foreach ( $data as $row ) {
      if ( $row['pid'] == $config['pid'] ) {  
        $result[$row['id']] = $row;
        $index[$row['id']] = & $result[$row['id']];
      } else {
        $index[$row['pid']]['son'][$row['id']] = $row;
        $index[$row['id']] = & $index[$row['pid']]['son'][$row['id']];
      }
    }
    return $this->_tree_to_array($result);
  }

  function _tree_to_array($arr) {
    $ret = array();
    foreach ($arr as $val) {
      if (isset($val['son'])) {
        $val['son'] = $this->_tree_to_array($val['son']);
      }
      $ret[] = $val;
    }
    return $ret;
  }

  function create($data) {
    $SysGroup = M('SysGroup');
    
    $data['level'] = $this->get_level($data['pid']);
    $ret = $SysGroup->add($data);
    if ($ret) {
      return ajax_arr('添加成功', TRUE, array(
        'id' => $ret
      ));
    } else {
      return ajax_arr('添加失败', FALSE);
    }
  }

  function update($id, $data) {
    $SysGroup = M('SysGroup');

    $data['level'] = $this->get_level( $data['pid']  );
    
    $ret = $SysGroup->where("id = %d", $id)->save($data);
    if ($ret) {
      //修改下属的 level;
      $this->_fix_level( $id , $data['level'] );
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }
  
  function _fix_level( $ids , $level ) {
    $SysGroup = M('SysGroup');
    $data = $SysGroup->field('GROUP_CONCAT(id) as ids')->where( 'pid in ('. $ids .')' , $ids )->find();
    

    if ( empty($data['ids'] ) ) {
      return ;
    } else {
      $new_array = array('level' => $level + 1 );

      $SysGroup->where( 'id in ('.$data['ids'].')'  )->save($new_array);
      $this->_fix_level($data['ids'], $$new_array['level'] );
    }
  }
    
  function delete($ids) {
    $SysGroup = M('SysGroup');
    
    $user_data = $this->get_user_role($ids);
    if ( $user_data ) {
      return ajax_arr('还有用户是该用户组下，请先将用户转移到其它用户组');
    }
    
    $ret = $SysGroup->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }

  function delete_user_group_by_user_id( $user_id ) {
    $SysUserGroup = M('SysUserGroup');
    $ret = $SysUserGroup->where( 'user_id = %d' , $user_id )->delete();
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }
  
  function get_user_group( $group_id ) {
    $SysUserGroup = M('SysUserGroup');
    $data = $SysUserGroup->where( 'group_id = %d' , $group_id )->find();
    return $data ? $data : array();
  }
  
  function get_family( $pid , $sys_type = 2 , $mer_id = 0 ) {
    $data = $this->get_by_cond(array(
      'sys_type' => $sys_type ,
      'mer_id' => $mer_id ,
      'status' => 1 ,
      'pid' => $pid ,
    ));
    
    if ( $pid == 0 ) {
      return $data ;
    } else {
      $pdata[0] = $this->get_by_id($pid);
      $pdata[0]['son'] = $data ;
      return $pdata ;
    }
  }
  
  function create_user_group( $user_id , $group_id_arr ) {
    $SysUserGroup = M('SysUserGroup');
    
    if ( !is_array($group_id_arr) ) {
      $group_id_arr = explode(',', $group_id_arr);
    }
    
    $status = TRUE  ;
    foreach ( $group_id_arr as $group_id ) {
      $ret = $SysUserGroup->add(array(
        'user_id' => $user_id ,
        'group_id' => $group_id ,
      ));
      if( !$ret ) {
        $status = FALSE ;
      }
    }
    
    if ( $status ) {
      return ajax_arr( '添加成功' , TRUE );
    } else {
      return ajax_arr( '添加失败' ) ;
    }
  }
  
  function update_user_group( $user_id , $group_id_arr ) {
    $change = FALSE ;
    if( !is_array($group_id_arr) ) {
      $group_id_arr = explode(',', $group_id_arr);
    }
    $SysUserGroup = M('SysUserGroup');
    
    $old_data = $SysUserGroup->where('user_id = %d ' , $user_id )->select();
    foreach ( $old_data as $row ) {
      $search_key = array_search($row['group_id'], $group_id_arr);
      if ( !$search_key ) {
        //删除
        $SysUserGroup->delete( $row['id'] );
        $change = TRUE ;
      } else {
        unset($group_id_arr[$search_key]);
      }
    }
    $new_arr = array();
    foreach ( $group_id_arr as $group_id ) {
      $new_arr[] = array(
        'user_id' => $user_id ,
        'group_id' => $group_id ,
      );
    }
    if ( !empty( $new_arr ) ) {
      $change = TRUE ;
      $SysUserGroup->addAll($new_arr);
    }
    return $change ? ajax_arr('编辑成功', TRUE ) : ajax_arr('编辑失败');
  }
}
